package com.lyh.crm.settings.web.controller;

import com.lyh.crm.settings.domain.DicType;
import com.lyh.crm.settings.domain.DicValue;
import com.lyh.crm.settings.domain.User;
import com.lyh.crm.settings.service.DicService;
import com.lyh.crm.settings.service.UserService;
import com.lyh.crm.settings.service.impl.DicServiceImpl;
import com.lyh.crm.settings.service.impl.UserServiceImpl;
import com.lyh.crm.utils.*;
import com.lyh.crm.vo.PaginationVO;
import com.lyh.crm.workbench.domain.Contacts;
import com.lyh.crm.workbench.domain.Tran;
import com.lyh.crm.workbench.service.ContactsService;
import com.lyh.crm.workbench.service.impl.ContactsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("进入到用户控制器");

        String path = request.getServletPath();

        if ("/settings/user/login.do".equals(path)) {

            login(request, response);

        } else if ("/settings/user/updatePwd.do".equals(path)) {

            updatePwd(request, response);

        } else if ("/settings/user/typeList.do".equals(path)) {

            typeList(request, response);

        }else if ("/settings/user/save.do".equals(path)) {

            save(request, response);

        } else if ("/settings/user/deleteByIds.do".equals(path)) {

            deleteByIds(request, response);

        } else if ("/settings/user/getDicType.do".equals(path)) {

            getDicType(request,response);

        } else if ("/settings/user/update.do".equals(path)) {

            update(request,response);

        }else if ("/settings/user/quit.do".equals(path)) {

            quit(request,response);

        }else if ("/settings/user/xxx.do".equals(path)) {

            //xxx(request,response);

        }

    }

    private void quit(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("执行用户退出功能");

        HttpSession session = request.getSession();

        session.removeAttribute("user");

        System.out.println("退出成功");
        PrintJson.printJsonFlag(response, true);
    }

    private void update(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("执行典类型或字典值修改操作");

        String typeDic = request.getParameter("typeDic");
        System.out.println("typeDic = " + typeDic);

        DicService ds = (DicService) ServiceFactory.getService(new DicServiceImpl());

        String code = request.getParameter("code");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        DicType dt = new DicType();
        dt.setCode(code);
        dt.setName(name);
        dt.setDescription(description);

        String id = request.getParameter("id");
        String value = request.getParameter("value");
        String text = request.getParameter("text");
        String orderNo = request.getParameter("orderNo");
        String typeCode = request.getParameter("typeCode");

        DicValue dv = new DicValue();
        dv.setId(id);
        dv.setValue(value);
        dv.setText(text);
        dv.setOrderNo(orderNo);
        dv.setTypeCode(typeCode);

        boolean flag = ds.update(dt,dv,typeDic);

        PrintJson.printJsonFlag(response, flag);
    }

    private void getDicType(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入到查询所有字典类型或字典值的操作");

        String code = request.getParameter("code");
        String id = request.getParameter("id");
        String typeDic = request.getParameter("typeDic");

        DicService ds = (DicService) ServiceFactory.getService(new DicServiceImpl());

        Map<String, Object> map = ds.getDicType(code,id,typeDic);

        PrintJson.printJsonObj(response, map);
    }

    private void deleteByIds(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("执行字典类型和字典值的删除操作");

        String codes[] = request.getParameterValues("code");
        if(codes!=null&&codes.length!=0) {
            for (String code : codes) {
                System.out.println("code = " + code);
            }
        }

        String ids[] = request.getParameterValues("id");
        if(ids!=null&&ids.length!=0){
            for (String id : ids) {
                System.out.println("id = " + id);
            }
        }

        DicService ds = (DicService) ServiceFactory.getService(new DicServiceImpl());

        boolean flag = ds.deleteByIds(codes,ids);

        PrintJson.printJsonFlag(response, flag);
    }

    private void save(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("执行字典类型和字典值的添加操作");
        String typeDic = request.getParameter("typeDic");
        System.out.println("typeDic = " + typeDic);

        DicService ds = (DicService) ServiceFactory.getService(new DicServiceImpl());

        String code = request.getParameter("code");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        DicType dt = new DicType();
        dt.setCode(code);
        dt.setName(name);
        dt.setDescription(description);

        String id = UUIDUtil.getUUID();
        String value = request.getParameter("value");
        String text = request.getParameter("text");
        String orderNo = request.getParameter("orderNo");
        String typeCode = request.getParameter("typeCode");

        DicValue dv = new DicValue();
        dv.setId(id);
        dv.setValue(value);
        dv.setText(text);
        dv.setOrderNo(orderNo);
        dv.setTypeCode(typeCode);

        boolean flag = ds.save(dt,dv,typeDic);

        PrintJson.printJsonFlag(response, flag);

    }

    private void typeList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String typeCode = request.getParameter("typeCode");
        System.out.println("typeCode = " + typeCode);
        String flag = "1";
        DicService ds = (DicService) ServiceFactory.getService(new DicServiceImpl());

        List<DicValue> dvList = null;
        List<DicType> dtList = null;
        if (typeCode!=null&&"dicType".equals(typeCode)){//查询所有字典类型
            dtList = ds.getAll2();
            PrintJson.printJsonObj(response, dtList);
        }else if (typeCode!=null&&"dicValue".equals(typeCode)) {//查询所有字典值
            dvList = ds.getAllValue();
            PrintJson.printJsonObj(response, dvList);
        } else {//条件查询字典值
            dvList = ds.getValueByCode(typeCode);

            request.removeAttribute("flag");
            request.removeAttribute("typeCode");
            request.removeAttribute("typeCode2");

            request.setAttribute("flag",flag);
            request.setAttribute("typeCode", dvList);
            request.setAttribute("typeCode2", typeCode);
            request.getRequestDispatcher("/settings/dictionary/value/index.jsp").forward(request, response);
        }


    }

    private void updatePwd(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入到修改密码操作");
        String id = request.getParameter("id");
        String newPwd = request.getParameter("newPwd");
        String oldPwd = request.getParameter("oldPwd");

        newPwd = MD5Util.getMD5(newPwd);
        oldPwd = MD5Util.getMD5(oldPwd);

        Map<String, String> map = new HashMap<String, String>();
        map.put("id", id);
        map.put("newPwd", newPwd);
        map.put("oldPwd", oldPwd);

        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());

        try {
            boolean flag = us.updatePwd(map);

            HttpSession session = request.getSession();

            session.removeAttribute("user");

            PrintJson.printJsonFlag(response, flag);
        } catch (Exception e) {
            e.printStackTrace();

            String msg = e.getMessage();

            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("success", false);
            map2.put("msg", msg);
            PrintJson.printJsonObj(response, map2);
        }


    }

    private void login(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("进入到验证登录操作");

        String loginAct = request.getParameter("loginAct");
        String loginPwd = request.getParameter("loginPwd");
        //将密码的明文形式转换为MD5的密文形式
        loginPwd = MD5Util.getMD5(loginPwd);
        //接收浏览器端的ip地址
        String ip = request.getRemoteAddr();
        System.out.println("--------------ip:" + ip);

        //未来业务层开发，统一使用代理类形态的接口对象
        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());

        try {

            User user = us.login(loginAct, loginPwd, ip);

            request.getSession().setAttribute("user", user);

            //如果程序执行到此处，说明业务层没有为controller抛出任何的异常
            //表示登录成功
            /*

                {"success":true}

             */
            PrintJson.printJsonFlag(response, true);

        } catch (Exception e) {
            e.printStackTrace();

            //一旦程序执行了catch块的信息，说明业务层为我们验证登录失败，为controller抛出了异常
            //表示登录失败
            /*

                {"success":true,"msg":?}

             */
            String msg = e.getMessage();
            /*

                我们现在作为contoller，需要为ajax请求提供多项信息

                可以有两种手段来处理：
                    （1）将多项信息打包成为map，将map解析为json串
                    （2）创建一个Vo
                            private boolean success;
                            private String msg;


                    如果对于展现的信息将来还会大量的使用，我们创建一个vo类，使用方便
                    如果对于展现的信息只有在这个需求中能够使用，我们使用map就可以了


             */
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", false);
            map.put("msg", msg);
            PrintJson.printJsonObj(response, map);


        }


    }
}




































